
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Jacob
 */
public class Img2Bin {
    private static int pointerX = 0;
    private static int pointerY = 0;
    private static BufferedImage img;
    private static int width;
    private static int height;
    public static void reset()
    {
        pointerX = 0;
        pointerY = 0;
        img = null;
        width = 0;
        height = 0;
    }
    private static int byteArrayToInt(byte [] b) {
        return (b[0] << 24)
                + ((b[1] & 0xFF) << 16)
                + ((b[2] & 0xFF) << 8)
                + (b[3] & 0xFF);
    }

    private static int getUnsigned(int b)
    {
        if(b < 0)
            return b + 256;
        else
            return b;
    }
    private static void incPointer()
    {
        pointerX++;
        if(pointerX >= width)
        {
            pointerX = 0;
            pointerY++;
        }
    }
    private static int[] get()
    {
        int rgb = img.getRGB(pointerX, pointerY);
        int r = (rgb >>> 16) & 0xFF;
        int g = (rgb >>> 8) & 0xFF;
        int b = (rgb >>> 0) & 0xFF;
        incPointer();
        return new int[]{r, g, b};
    }
    public static byte[] getBytes(BufferedImage image, int length)
    { 
        reset();
        Img2Bin.img = image;
        try
        {
            width = img.getWidth();
            height = img.getHeight();

            byte[] bytes = new byte[length];
            int ptr = 0;
            while(ptr < length)
            {
                int[] c = get();
                bytes[ptr] = (byte) c[0];
                ptr++;
                if(ptr >= length)
                    break;
                bytes[ptr] = (byte) c[1];
                ptr++;
                if(ptr >= length)
                    break;
                bytes[ptr] = (byte) c[2];
                ptr++;
            }
            return bytes;
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            return null;
        }
    }
    public static void doConvert(BufferedImage img, File file, int length)
    {

        try
        {
            byte[] bytes = getBytes(img, length);
            FileOutputStream out = new FileOutputStream(file);
            out.write(bytes);
            out.close();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
}
